package com.webtest.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.webtest.entity.Ad;
import com.webtest.service.AdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/admin")
public class AdminAdController {
    @Autowired
    private AdService adService;

    //通过图书id获取图书信息，传给前端回显
    @GetMapping("/ad/{id}/update")
    public String toUpdateBooks(@PathVariable Long id, Model model) {
        LambdaQueryWrapper<Ad> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Ad::getShelfId, id);
        Ad ad = adService.getOne(wrapper);
        if (ad == null) {
            ad = new Ad();
            ad.setShelfId(id);
        }
        model.addAttribute("ad", ad);
        return "admin/ad-input";
    }

    @PostMapping("/ad/update")
    public String updateAd(Ad ad, RedirectAttributes attributes) {
        if (ad.getId() == null) {
            adService.save(ad);
        } else {
            adService.updateById(ad);
        }
        attributes.addFlashAttribute("message", "修改成功！！！");
        return "redirect:/admin/shelf";
    }
}
